<template>
  <a-cascader
    v-model="checkedsValue"
    :options="optionDatas"
    placeholder="请选择"
    v-bind="$attrs"
  />
</template>
<script>
import { post, get } from 'server/axios'
import { evalPropChain } from 'utils/utils.js'
const AXIOS_METHOD = {
  get: get,
  post: post
}
export default {
  name: 'cpsCascader',
  props: {
    value: [String, Number, Array],
    url: String,
    // 请求接口参数
    params: {
      type: Object,
      default: () => {
        return {}
      }
    },
    method: {
      type: String,
      default: 'post'
    },
    // 支持自定义传options
    options: {
      type: Array,
      default: () => []
    },
    respField: {
      type: String,
      default: 'data'
    },
    immediate: {
      type: Boolean,
      default: true
    },
    setDisabled: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      reqParams: this.params,
      optionDatas: this.options || []
    }
  },
  computed: {
    checkedsValue: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },
  watch: {
    params(newV, v) {
      if (JSON.stringify(newV) !== JSON.stringify(v)) {
        if (this.url) {
          this.reqParams = this.params
          this.queryServiceData()
        }
      }
    },
    immediate: {
      handler(val) {
        if (this.url && this.immediate) {
          this.queryServiceData()
        }
      },
      immediate: true
    }
  },
  methods: {
    getServeUrl() {
      return this.url.startsWith('http')
        ? this.url
        : `${process.env.VUE_APP_CONFIG}/${this.url}`
    },
    async queryServiceData() {
      const resp = await AXIOS_METHOD[this.method.toLowerCase()](
        this.getServeUrl(),
        this.reqParams
      )
      if (resp.success) {
        // eslint-disable-next-line no-eval

        this.optionDatas = evalPropChain(resp, this.respField)
        if (this.setDisabled) {
          const childrenKey = attrs.fieldNames.children || 'children'
          const deepOption = options => {
            options.map(item => {
              item.disabled = this.setDisabled(item)
              item[childrenKey]?.length && deepOption(item[childrenKey])
            })
          }
          deepOption(this.optionDatas)
        }
        this.$emit('update:options', this.optionDatas)
        this.$forceUpdate()
      }
    }
  }
}
</script>
<style lang="scss" scoped></style>
